/**
 * 检查学生的身份
 */

 const jwt = require('jsonwebtoken')
 const redis = require('redis')
 const configs = require('../config')
 const $ = require('../utils/common')
 const redis_config = configs.redis_config
 const key = configs.json_web_token_key
 const general_api = configs.general_api

 const check_student_permission = async function(req, res, next) {

     try {

        const path = req._parsedUrl.pathname

        req.body.token = req.body.token || req.query.token
    
        if (!req.body.token) {
            $.sendMessage(res, 1015, 'token没有传')
            return
        }
    
        // $.log('学生-当前路径:', path)
        // $.log('学生-当前token:', req.body.token)
    
        
        //解析token
        var token = await jwt.verify(req.body.token, key, (err, data) => {
            if (err) {
                $.sendMessage(res, 1006, 'token解析失败')
                return
            }
            return data
        })
        // $.log('解析后的token：', token)

        // 通用api
        if (!general_api.includes(path)) {
            if (token.user_role != 'student') {
                $.sendMessage(res, 1014, '您没有权限访问')
                return
            }
        }
        

        // 从redis获取token
        var redis_client = await redis.createClient({port:redis_config.PORT, host: redis_config.HOST,no_ready_check: true})
        await redis_client.auth(configs.redis_config.PASSWORD)
        redis_client.get(token.user_name, (err, data) => {
            // $.log('data from redis: ', data)

            if (err) {
                $.sendMessage(res, 1012, 'redis服务器出错，请联系管理员')
                return
            }

            if (data == null) {
                $.sendMessage(res, 1011, 'token过期请重新登陆')
                return
            }

            // $.log('type of req.body.token:', typeof token)
            // $.log('type of token from redis:', typeof data)
            // $.log('req.body.token:', req.body.token)
            // $.log('token from redis:', data)

            if (data.trim() != req.body.token.trim() ) {
                $.sendMessage(res, 1013, '从redis获取的 token和 传来的token不一致3')
                return
            }

            // 身份验证通过，去执行后面代码
            req['user_name'] = token.user_name
            next()
            return
        })

     }

     catch(error) {
         $.sendMessage(res, 0000, error)
         return
     }
    
 }

 module.exports = check_student_permission